#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/12/1 21:14
    Desc  :
--------------------------------------
"""
from collections import Callable
from functools import wraps
from typing import Dict, cast, Any

import requests
from django.http import JsonResponse
from jsonrpcclient import parse, Ok
from jsonrpcserver import Result

Method = Callable[..., Result]
Methods = Dict[str, Method]

global_methods = dict()


# def rpc_client(f: Method, name: str):
#     def view_decorator(func: Method):
#         @wraps(func)
#         def wrapper(request, *args, **kwargs):
#             nonlocal name
#
#             global_methods[name or func.__name__] = func
#
#             return func(request, *args, **kwargs)
#
#         return wrapper
#
#     return view_decorator(f) if callable(f) else cast(Method, view_decorator(f))


def JsonRpcClient(url: str, func_name: str, params: Any):

    def view_decorator(func):
        @wraps(func)
        def wrapper(request, *args, **kwargs):

            if request.method == 'POST':
                resp = requests.post(url = "http://127.0.0.1:9002/rpc",
                              json = request(method = func_name, params = params))
            elif request.method == 'GET':
                resp = requests.get(url = "http://127.0.0.1:9002/rpc",
                                     json = request(method = func_name, params = params))
            parsed = parse(resp.json())
            if isinstance(parsed, Ok):
                JsonResponse(data = parsed.result)
            else:
                JsonResponse(data = parsed.result, status = 400)

        return wrapper

    return view_decorator